/*
 * Crawler.cpp
 *
 *  Created on: 6 mei 2013
 *      Author: Wietse
 */


#include "Crawler.h"
#include "Data.h"
#include "Swarm.h"

#include <iostream>
#include <ctime>

/**
 * Default constructor.
 */
Crawler::Crawler()
{	sourceType 				= CRAWLER;
	this->ID				= 0;
	this->position 			= Position(0.0, 0.0);
	this->angle 			= rand() % 360;
	this->movement_timer	= 0.0;
	this->message_timer 	= 0.0;
	this->covered 			= false;
}

/**
 * Preferred constructor
 */
Crawler::Crawler(int ID, Position pos)
{	sourceType 				= CRAWLER;
	this->ID 				= ID;
	this->position 			= pos;
	this->angle				= rand() % 360;
	this->movement_timer	= 0.0;
	this->message_timer 	= 0.0;
	this->covered 			= false;
}

/**
 * Default destructor
 */
Crawler::~Crawler()
{
}

bool Crawler::getCovered()
{
	return covered;
}

void Crawler::setCovered(bool cov)
{
	covered = cov;
}

/**
 * Check if the given position is in range of the message
 */
bool Crawler::inRange(Position *other)
{
	// Calculate the Euclidian distance
	double dis = position.distance(other);

	// Check if the distance is smaller than the radius of the message
	if(dis < AGENT_CRAWLER_DETECTION_RANGE)
	{
		return true;
	}
	return false;
}


/**
 * Update the Crawler
 */
void Crawler::update(Swarm *swarm, double deltaTime)
{
	// Increment the timer
	movement_timer += deltaTime;

	// Check if timer expired
	if(movement_timer > CRAWLER_MESSAGE_TIME)
	{
		// Determine a random angle
		angle = rand() % 360;

		// Reset the timer
		movement_timer = 0.0;
	}

	// Store old position in case the crawler goes out of bounds
	position.backup();

	// Update position
	position.addX( CRAWLER_SPEED*deltaTime*cos(angle) );
	position.addZ( CRAWLER_SPEED*deltaTime*sin(angle) );

	// Check if the crawler went out of bounds
	if(position.getX() < xwmin || position.getX() > xwmax || position.getZ() < zwmin || position.getZ() > zwmax)
	{
		// Reset position
		position.restore();
	}
}

/**
 * Draw the Crawler on screen
 */
void Crawler::display()
{
	// Set the color of the crawler based on if it is covered or not
	if(covered)
	{
		glColor3f(0.0, 1.0, 0.0);	// Green
	}
	else
	{
		glColor3f(1.0, 0.0, 0.0);	// Green
	}

	// Draw Crawler as a square
	glBegin(GL_QUADS);
	glVertex3f(position.getX()-CRAWLER_WIDTH/2, position.getZ(), 0.0);
	glVertex3f(position.getX(), position.getZ()-CRAWLER_HEIGHT/2, 0.0);
	glVertex3f(position.getX()+CRAWLER_WIDTH/2, position.getZ(), 0.0);
	glVertex3f(position.getX(), position.getZ()+CRAWLER_HEIGHT/2, 0.0);
	glEnd();
}

